/**
 * @author YinHang
 * OA核心api.
 * 需要util.js,jTemplates.js,jQuery.js的支持.
 */

;(function () {
	window.oacore = {
		UI: {
			render: render,
			uiBase: "/ui/",
			uiSuffix: "html",
			outputPagBar: generatePaging,
			FloatBox: FloatBox
		},
		Widget: {
			
		},
		Code: {
			scriptBase: "/javascript/"
		},
		Util: {
			goUrl: goUrl,
			openUrl: openUrl,
			action: action,
			loadScriptQueue: loadScriptQueue,
			getCssList: getCssList,
			autoSaveWithWebOffice: autoSaveWithWebOffice,
			autoSave: autoSave
		},
		Data: {
			requestProxy: requestProxy
		}
	};
	
	/**
	 * url
	 * form
	 * beforeUnloadAutosave
	 * afterSave
	 * beforeSave
	 * callback
	 * interval
	 */
	function autoSave(options) {
		var $form = $(options.form);
		function saving() {
			if($form.data("stopAutoSave") == true)
				return;
			$form.data("autoSaving", true);
			if(options.beforeSave)
				if(options.beforeSave() == false)
					return;
			$.util.Data.request({
				url: options.url || $form.attr("action"),
				data: $form.formSerialize(),
				type: "post",
				async: false,
				dataType: "json",
				error: function () {
					$form.data("autoSaving", false);
				},
				success: function (data) {
					if(options.afterSave)
						options.afterSave();
					if(options.callback)
						options.callback(data);
					$form.data("autoSaving", false);
				}
			});
		}
		setInterval(saving, options.interval || 3 * 60 * 1000);
		if(options.beforeUnloadAutosave != false)
			$(window).bind("beforeunload", saving);
	};
	
	function autoSaveWithWebOffice(options) {
		var _beforeSave = options.beforeSave;
		options.beforeSave = function () {
			if(window.SaveDocument)
				window.SaveDocument();
			if(_beforeSave)
				return _beforeSave();
		};
		autoSave(options);
	};
	
	function goUrl(address)
	{
		location.href = encodeURI(encodeURI(path + address));
	};
	
	function requestProxy(options) {
		var requestUrl = options.url;
		options.url = path + "/ajax/requestProxy.action";
		options.data = options.data ? options.data : {};
		options.cache = true;
		$.extend(options.data, {uri : requestUrl});
		$.util.Data.request(options);
	};
	
	var openCount = 0;
	
	function openUrl(address, width, height)
	{
		width = width ? width : "800";
		height = height ? height : "600";
		//if($.browser.msie)
		//{
			var rndParam = "";
			if(address.split("?").length <= 1)
				rndParam = "?_=" + new Date().getTime() + ( ++ openCount );
			else {
				rndParam = "&_=" + new Date().getTime() + ( ++ openCount );
			}
		//	window.showModelessDialog(path + address + rndParam, null, "dialogWidth:" + width + "px;dialogHeight:" + height + "px;dialogLeft:300;dialogTop:80;resizable: no;");
		//}
	//	else
		//{
			window.open(path + address + rndParam, address.match(/[\d\w]+/g).join(""), "width=" + width + ", height=" + height + ", resizable=no, scrollbars=yes, top=0, left=0, toolbar=no, menubar=no, location=no, status=no");
		//}
	};
	
	function action(address)
	{
		this.action = path + address;
	};
	
	function opresult() {
		
	};
	
	/**
	 * id: id
	 * className: className
	 */
	function FloatBox(params)
	{
		this.content = $("<div>").addClass("float_box");
		var host = this;
		this.autoDestroyFun = function () {
			host.destroy();
		};
		this.autoHideFun = function () {
			host.hide();
		};
		this.stopPropagationFun = function (event) {
			event.stopPropagation();
		};
		if(params)
		{
			this.content.attr("id", params.id);
			if(params.className)
				this.content.addClass(params.className);
		}
	};
	
	FloatBox.prototype.setContent = function (content) {
		this.content.empty().append(content);
	};
	
	FloatBox.prototype.destroy = function () {
		this.autoDestroy(false);
		this.content.empty().remove();
		if(this.onDestroy)
			this.onDestroy();
	};
	
	FloatBox.prototype.hide = function () {
		this.content.hide();
		if(this.onHide)
			this.onHide();
	};
	
	FloatBox.prototype.onDestroy = function () {
		
	};
	
	FloatBox.prototype.show = function () {
		this.content.show();
	};
	
	FloatBox.prototype.autoDestroy = function (auto) {
		if(auto)
		{
			$(document.documentElement).bind("click", this.autoDestroyFun);
			this.content.bind("click", this.stopPropagationFun);
		}
		else
		{
			$(document.documentElement).unbind("click", this.autoDestroyFun);
			this.content.unbind("click", this.stopPropagationFun);
		}
	};
	
	FloatBox.prototype.autoHide = function (auto) {
		if(auto)
		{
			$(document.documentElement).bind("click", this.autoHideFun);
			this.content.bind("click", this.stopPropagationFun);
		}
		else
		{
			$(document.documentElement).unbind("click", this.autoHideFun);
			this.content.unbind("click", this.stopPropagationFun);
		}
	};
	
	function generatePaging(count, size, cur) {
		var content = $("<div>");
		if(cur > 1)
			content.html("<button id='prevPageBtn'><span></span></button>");
		var startPage = cur;
		var loopCount = parseInt( size / 2 );
		if(loopCount == size / 2)
			-- loopCount;
		var leftInc = cur + loopCount - count;
		if(leftInc > 0)
			loopCount += leftInc;
		for(var i=0;i<loopCount;++i)
		{
			if(startPage <= 1)
				break;
			-- startPage;
		}
		for(var i=0;i<size;++i)
		{
			if(startPage != cur)
				content.append("<a class='pageTag' id='" + startPage + "_Page' href='javascript:void(0);'>" + startPage + "</a>");
			else
			{
				content.append("<a class='pageTag pt-selected' id='" + startPage + "_Page' href='javascript:void(0);'>" + startPage + "</a>");
			}
			if(++ startPage > count)
				break;
		}
		if(cur < count)
			content.append("<button id='nextPageBtn'><span></span></button>");
		return content.children();
	};
	
	
	function processParams(actionType, source) 
	{
		if(source)
		{
			for(var key in source)
			{
				var newKey = actionType.params[key];
				if(newKey)
				{
					if(newKey != key)
					{
						source[newKey] = source[key];
						delete source[key];
					}
				}
			}
		}
		return source;
	};
	
	function requestAction(params) {
		params.url = params.actionType.url;
		params.data = processParams(params.actionType, params.data);
		params.type = params.type ? params.type : "post";
		$.util.Data.request(params);
	};
	
	function getScript(url, callback) {
		if(_MEM_DATA.data(url))
			return;
		_MEM_DATA.data(url, true);
		$.getScript(url, callback);
	};
	
	function getCss(url) {
		if(_MEM_DATA.data(url))
			return;
		_MEM_DATA.data(url, true);
		var head = document.getElementsByTagName("head");
		if(!head || head.length <= 0)
			head = [document.createElement("head")];
		var link = document.createElement("link");
		link.href = url;
		link.rel = "stylesheet";
		link.type = "text/css";
		head[0].appendChild(link);
	};
	
	function getCssList(cssList) {
		for(var i=0;i<cssList.length;++i)
			getCss(cssList[i]);
	};
	
	function loadScriptQueue(scriptQueue, callback) {
		var index = 0;
		var loader = function () {
			if(scriptQueue[index])
			{
				var curIndex = index;
				++ index;
				$.ajax({
					  url: scriptQueue[curIndex],
					  dataType: "script",
					  success: loader,
					  buffer: true,
					  cache: true
					});
			}
			else if(callback)
			{
				callback();	
			}
		};
		loader();
	};
	
	function render(ui, data, host, callback, options) {
		var url = "";
		if(ui.charAt(0) == "/")
			url = ui;
		else
		{
			url = oacore.UI.uiBase + ui;
		}
		if(ui.indexOf('.') == -1)
			url += "." + oacore.UI.uiSuffix;
		$.util.Data.request({
			url: path + url,
			dataType: "text",
			cache: true,
			success: function (uiData) {
				if($(host).setTemplate)
					$(host).setTemplate(uiData, options ? options.includes : null, options).processTemplate(data);
				if(callback)
					callback();
			},
			buffer: true
		});
	};
	
	var _MEM_DATA = $({});
})();

/**
 * 对话框控件
 * 基于oacore,jquery-treeview.js,treeview.js,jquery-ui.js.
 */
;(function () {
	//系统alert请用window.alert调用
	/**
	 * data: 初始化数据.
	 * ui: ui.
	 * callback: callback
	 * options: jq-ui options.
	 */
	function Dialog(params)
	{
		var content = $("<div>");
		oacore.UI.render(params.ui, params.data, content, function () {
			if($.browser.msie)
				$("select").hide();
			var _onClose = params.options.close;
			$.extend(params.options, {
				close: function () {
					$(this).dialog("open").dialog("destroy").remove();
					if($.browser.msie)
						$("select").show();
					if(_onClose)
						_onClose();
				}
			});
			if(params.options)
			{
				if(!params.options.dialogClass)
					params.options.dialogClass = "oa-commons-dialog";
			}
			content.appendTo(document.body).dialog(params.options);
			if(params.options)
			{
				if(params.options.header == false)
					$("div.ui-dialog-titlebar").remove();
			}
			
			if(params.callback)
				params.callback(content);
		});
	};
	
	oacore.Widget.Dialog = Dialog;
	
	/**
	 * title: 标题
	 * tip: 提示内容
	 * onOk: callback
	 * onCancal: callback
	 */
	function confirm(title, tip, onOk, onCancel)
	{
		//启用系统对话框
		if(window.confirm(tip))
		{
			if(onOk)
				onOk();
		}
		else
		{
			if(onCancel)
				onCancel();
		}
		return;
		//放弃模拟对话框
		var content = $("<div>");
		if(!title)
			title = "提示";
		if(!tip)
			tip = "确认?";
		new oacore.Widget.Dialog({
			ui: "dialog/confirm",
			data: tip,
			options: {
				modal: true,
				width: 320,
				height: 180,
				title: title,
				resizable: false,
				buttons: [
				          {
				                text: "确定",
				                click: function() {
				        	  		if(onOk)
				        	  		{
				        	  			if(onOk() != false)
				        	  				$(this).dialog("close");
				        	  		}
				        	  		else
				        	  		{
				        	  			$(this).dialog("close");
				        	  		}
				                }
					       },
					       {
				                text: "取消",
				                click: function() {
				    	   			if(onCancel)
				        	  		{
				        	  			if(onCancel() != false)
				        	  				$(this).dialog("close");
				        	  		}
				        	  		else
				        	  		{
				        	  			$(this).dialog("close");
				        	  		}
			                	}
					       }
				          ]
				}
			});
	};
	
	oacore.Widget.Dialog.confirm = confirm;
	
	function alert(title, tip, onOk)
	{
		//启用系统对话框
		window.alert(tip);
		return;
		//放弃模拟对话框
		var content = $("<div>");
		if(!title)
			title = "提示";
		if(!tip)
			tip = "确认?";
		new oacore.Widget.Dialog({
			ui: "dialog/confirm",
			data: tip,
			options: {
				modal: true,
				width: 320,
				height: 180,
				title: title,
				resizable: false,
				buttons: [
				          {
				                text: "确定",
				                click: function() {
				        	  		if(onOk)
				        	  		{
				        	  			if(onOk() != false)
				        	  				$(this).dialog("close");
				        	  		}
				        	  		else
				        	  		{
				        	  			$(this).dialog("close");
				        	  		}
				                }
					       }
				          ]
				}
			});
	};
	
	oacore.Widget.Dialog.alert = alert;
})();
